<?php
class Generate extends Object
{
    public static function Schema($schema, $template_file = null)
    {
        $tables = TablesModel::GetInstance()->GetNameBySchema($schema);
        foreach ($tables as $table)
        {
            self::Model($table, $template_file);
        }
    }

    public static function Model($table, $template_file = null)
    {
        try
        {
            $table = strtolower($table);
            $class = String::Pascalize($table).'Model';
            if (!$template_file)
                $template_file = 'ModelTemp';

            $file = AppConfig::GetInstance()->DIR_GEN.DS.$class.'.php';

            $template = self::GetTemplate("$template_file.php");
            $template->Replace('class', $class);
            FileHandler::Write($file, $template->Render());
            MessageBase::Confirm("$file\n");
        }
        catch (Exception $ex)
        {
            MessageBase::Warning($ex->getMessage());
        }
    }

    public static function ItemClass($table)
    {
        try
        {
            $table = strtolower($table);
            $class = String::Pascalize($table);

            $model = ModelBase::GetInstanceByName($table);

            $template = self::GetTemplate('item_temp.php');
            $template->Replace('class', $class);
            $template->Repeat('field', $model->GetFields(), array($this, 'Format'));

            $file = AppConfig::GetInstance()->DIR_GEN.DS.$class.'.php';
            FileHandler::Write($file, $template->Render());
            MessageBase::Confirm("$file\n");
        }
        catch (Exception $ex)
        {
            MessageBase::Warning($ex->getMessage());
        }
    }

    public function Format($item)
    {
        $item['name'] = String::Camelize($item['name']);
        return $item;
    }

    public static function GetTemplate($name)
    {
        return new Template($name, GenConfig::GetInstance()->DIR_CURRENT_TEMPLATE);
    }
}
?>
